import {
  formatTime
} from '../../../utils/util';
import {
  OrderStatus,
  LogisticsIconMap
} from '../config';
import {
  fetchBusinessTime,
  fetchOrderDetail,
} from '../../../services/order/orderDetail';
import Toast from '/tdesign-miniprogram/toast/index';
import {
  getAddressPromise
} from '../../usercenter/address/list/util';
import {
  ds
} from '../../../tools/data'
import {
  shops
} from '../../../tools/shops'
import {
  pay
} from '../../../tools/pay';
import {
  ui
} from '../../../tools/ui';
import {
  pages
} from '../../../tools/pages';
import {
  checkTool
} from '../../../tools/check';
import {
  resource
} from '../../../static/resource';
import {
  dsx
} from '../../../tools/datax';
import {
  nav2
} from '../../../tools/nav2';
import {
  exTool
} from '../../usercenter/exTicket/exTool';
import {
  dateTool
} from '../../../tools/date';
import {
  dsFiles
} from '~/tools/dsFiles'
import {
  coupon
} from '~/tools/coupon';

const _ = dsx.cmd

Page({
  data: {
    resource,
    pageLoading: true,
    user: '',
    orderUser: '',
    order: '', // 后台返回的原始数据
    _order: {}, // 内部使用和提供给 order-card 的数据
    storeDetail: {},
    countDownTime: null,
    addressEditable: false,
    backRefresh: false, // 用于接收其他页面back时的状态
    formatCreateTime: '', //格式化订单创建时间
    logisticsNodes: [],
    /** 订单评论状态 */
    orderHasCommented: true,
    addr: {},
    shop: {},
    deliveryMan: null
  },

  onLoad(query) {
    this.query = query
    this.orderNo = query.orderNo;
    this.init();
    this.navbar = this.selectComponent('#navbar');
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },

  onShow() {
    // 当从其他页面返回，并且 backRefresh 被置为 true 时，刷新数据
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({
      backRefresh: false
    });
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  onImgError(e) {
    if (e.detail) {
      console.error('img 加载失败');
    }
  },

  // 页面初始化，会展示pageLoading
  async init() {
    ui.loading()
    this.setData({
      pageLoading: true
    });
    await this.loadUser()
    this.getStoreDetail();
    this.getDetail()
      .then(() => {
        this.setData({
          pageLoading: false
        });
        ui.loading(false)
      })
      .catch((e) => {
        ui.loading(false)
        console.error(e);
      });
  },
  initHasCoupon(order) {
    this.setData({
      hasCoupon: coupon.isCouponValid(order)
    })
  },
  initChat() {
    const {
      order,
      user,
      orderUser,
      shop
    } = this.data
    // console.log(this.data)
    if (user._openid == order._openid) { // 自己的订单
      this.setData({
        chatTarget: 'self'
      })
    } else {
      this.setData({
        chooseTarget: true,
        targetActions: {
          "others": "联系客户",
          "list": "进入聊天列表"
        },
        sessionOpenId: orderUser._openid,
        from: 'orderDetail',
        autoMsg: {
          orderId: order._id,
          ticket: Boolean(order.ticketInfo),
          shopName: shop.name
        },
        notifyMobile: orderUser.phoneNumber
      })
    }
  },
  async loadOrderUser() {
    const order = this.data.order
    return await dsx.coll('users')
      .where({
        _openid: _.eq(order._openid)
      })
      .field({
        personInfo: true,
        phoneNumber: true,
        _openid: true
      })
      .get()
      .then(res => {
        const orderUser = res.data[0]
        this.setData({
          orderUser
        })
        this.initChat()
        return res
      })
  },
  async loadUser() {
    await new Promise(resolve => {
      ds.cloudGetByOpenid('users', res => {
        const user = res.result.data[0]
        this.setData({
          user
        })
        resolve(user)
      })
    })
  },
  // 页面刷新，展示下拉刷新
  onRefresh() {
    this.onLoad(this.query)
  },
  // 页面刷新，展示下拉刷新
  onPullDownRefresh_(e) {
    const {
      callback
    } = e.detail;
    return this.getDetail().then(() => callback && callback());
  },
  // 获取订单信息
  fetchOrderDetail_(params) {
    // console.log(params)
    const orderId = params.parameter

    return new Promise((resolve, reject) => {
      // 当前订单
      return ds.coll('orders')
        .where({
          _id: params.parameter
        })
        .get()
        .then(ordersRes => {
          // console.log('order res', res)
          // 送水地址
          const order = ordersRes.data[0]
          ds.coll('delivery_addr')
            .where({
              _openid: _.eq(order._openid)
            })
            .get()
            .then(res => {
              // console.log(' addr res', res)
              const addr = res.data[0]
              this.setData({
                addr
              })

              if (addr && addr.shop) {
                const shop = shops.getShop(addr.shop)
                this.setData({
                  shop
                })
              }
              resolve(ordersRes)
            })
        })
    })
  },
  getDetail() {
    const params = {
      parameter: this.orderNo,
    };
    // console.log(params)
    return this.fetchOrderDetail_(params).then((res) => {
      // console.log(res)
      const order = res.data[0];
      const _order = {
        id: order.orderId,
        orderNo: order.orderNo,
        parentOrderNo: order.parentOrderNo,
        storeId: order.storeId,
        storeName: this.data.shop.name || '万家顺送水', // order.storeName,
        status: order.orderStatus,
        statusDesc: order.orderStatusName,
        amount: order.paymentAmount,
        totalAmount: order.goodsAmountApp,
        logisticsNo: '', // order.logisticsVO.logisticsNo,
        goodsList: (order.orderItemVOs || []).map((goods) =>
          Object.assign({}, goods, {
            id: goods.id,
            thumb: goods.goodsPictureUrl,
            title: goods.goodsName,
            skuId: goods.skuId,
            spuId: goods.spuId,
            specs: (goods.specifications || []).map((s) => s.specValue),
            price: goods.tagPrice ? goods.tagPrice : goods.actualPrice, // 商品销售单价, 优先取限时活动价
            num: goods.buyQuantity,
            titlePrefixTags: goods.tagText ? [{
              text: goods.tagText
            }] : [],
            buttons: goods.buttonVOs || [],
          }),
        ),
        buttons: order.buttonVOs || [],
        createTime: order.createTime,
        receiverAddress: '', // this.composeAddress(order),
        groupInfoVo: order.groupInfoVo,
      };
      if (order.deductFeeInfo) order.deductFeeInfo.fee = Number(order.deductFeeInfo.fee)
      // console.log(order)
      OrderStatus.descRefoundStatus(order.refoundInfo)

      this.setData({
        order,
        _order,
        formatCreateTime: formatTime(
          parseFloat(`${order.createTime}`),
          'YYYY-MM-DD HH:mm',
        ), // 格式化订单创建时间
        countDownTime: this.computeCountDownTime(order),
        addressEditable: [OrderStatus.PENDING_PAYMENT, OrderStatus.PENDING_DELIVERY].includes(
          order.orderStatus,
        ) && order.orderSubStatus !== -1, // 订单正在取消审核时不允许修改地址（但是返回的状态码与待发货一致）
        isPaid: '', // !!order.paymentVO.paySuccessTime,
        invoiceStatus: '', // this.datermineInvoiceStatus(order),
        invoiceDesc: order.invoiceDesc,
        invoiceType: order.invoiceVO?.invoiceType === 5 ? '电子普通发票' : '不开发票', //是否开票 0-不开 5-电子发票
        logisticsNodes: this.flattenNodes(order.trajectoryVos || []),
      });

      this.showDeliveryInfo(order)
      this.loadOrderUser()
      this.initHasCoupon(order)
    });
  },
  showDeliveryInfo(order) {
    // console.log(order)
    if (!order.deliveryMan) return
    ds.coll('users')
      .where({
        _openid: order.deliveryMan
      })
      .get()
      .then(res => {
        // console.log(res)
        const deliveryMan = res.data[0]
        this.setData({
          deliveryMan
        })
      })
  },
  getCouponTap() {
    const {
      order,
      user
    } = this.data
    wx.navigateTo({
      url: `/pages/order/order-detail/get-coupon/get-coupon?order=${JSON.stringify(order)}&user=${JSON.stringify(user)}`,
    })
  },
  giveawayTap() {
    const {
      order
    } = this.data
    const param = {
      id: order._id,
      openid: order._openid,
      ticketInfo: order.ticketInfo
    }
    wx.navigateTo({
      url: `/pages/order/order-detail/giveaway-ticket/index?data=${JSON.stringify(param)}`,
    })
  },
  proofImageTap() {
    let {
      showProofImage
    } = this.data
    this.setData({
      showProofImage: !showProofImage
    })
  },
  // 删除订单
  onDel(e) {
    ui.confirm('确定删除吗？', res => {
      if (!res) return

      const _id = e.target.dataset.id
      ds.remove('orders', {
        _id
      }, res => {
        pages.back(prePage => {
          prePage.onRefresh()
        })
      })
    })
  },
  onDeleteProofImageTap(e) {
    const id = ui.eventData(e, 'id'),
      that = this
    ui.confirm('确定删除吗？', res => {
      if (!res) return

      ui.loading()
      ds.cloudUpdate('orders', id, {
        deliveryProof: ''
      }, res => {
        const success = res.result.errMsg.endsWith(":ok")
        ui.loading(false)
        ui.toast(success)
        if (success) that.setData({
          'order.deliveryProof': ''
        })

      })
    })
  },
  onTakePhotoTap(e) {
    const id = ui.eventData(e, 'id'),
      that = this
    dsFiles.chooseMedia({
      mediaType: ['image'],
      success: function (file) {
        ui.loading(true, '文件上传中...')
        dsFiles.uploadFile(file, 'proofImage', fileId => {
          ds.cloudUpdate('orders', id, {
            deliveryProof: fileId
          }, res => {
            const success = res.result.errMsg.endsWith(":ok")
            ui.loading(false)
            ui.toast(success)
            if (success) that.setData({
              'order.deliveryProof': fileId
            })
          })
        })
      }
    })
  },
  // 同意退款
  onAgreeRefoundTap() {
    const {
      order
    } = this.data
    // console.log(order)
    const totalFee = order.totalFee, // yuan
      refoundFee = order.refoundInfo.fee // yuan
    pay.refound({
      totalFee,
      refoundFee,
      outTradeNo: order.outTradeNo,
      title: '退款￥' + refoundFee.toFixed(2)
    }, (success, res) => {
      if (!success) return
      const status = (Math.round(refoundFee * 100) >= Math.round(totalFee * 100) ? '已退款' : undefined)
      ds.cloudUpdate('orders', order._id, {
        refoundInfo: {
          status: 'success',
          updateTime: new Date().getTime()
        },
        status
      }, res => {
        ui.toast(success)
        pages.back(prePage => {
          prePage.refreshList(prePage.data.status)
        })
      })
    })
  },
  async onCancelRefoundTap() { // 拒绝退款
    if (!await ui.confirmx("取消退款吗？")) return
    const {
      order
    } = this.data
    // console.log(this.data.order)

    ui.loading()
    dsx.cloudUpdate('orders', order._id, {
      refoundInfo: {
        status: 'cancel'
      }
    }).then(res => {
      ui.toast(res.result?.errMsg.endsWith(':ok'), null, () => {
        this.onRefresh()
      })
    })
  },
  // 修改价格
  onUpdateTotalFee() {
    const {
      order
    } = this.data
    ui.text('输入修改后价格', `输入数字`, (confirm, txt) => {
      if (!confirm) return
      checkTool.check([{
        value: txt,
        fn: txt => +txt > 0 && checkTool.test(txt, checkTool.CommonRegex.decimal),
      }])
      ui.loading()
      ds.cloudUpdate('orders', order._id, {
        totalFee: +txt
      }, res => {
        ui.loading(false)
        this.onRefresh()
      })
    })
  },
  onUpdateUsage() {
    const {
      order
    } = this.data
    const ticketInfo = this.data.order.ticketInfo
    ui.text('设置已兑换桶数', `0到${ticketInfo.totalAmount}`, (ok, input) => {
      if (!ok) return
      let used = 0
      checkTool.check([{
        value: input,
        title: '用量',
        fn: val => {
          const isInt = checkTool.test(val.trim(), checkTool.CommonRegex.integer)
          used = Number(input.trim())
          return isInt && (used >= 0) && (used <= Number(ticketInfo.totalAmount))
        }
      }])
      ui.loading()
      exTool.setUsage(order, used).then(res => {
        ui.loading(false)
        ui.toast(res?.result?.errMsg.endsWith(':ok'), '', () => {
          this.onRefresh()
        })

      })
    })
  },
  // 展开物流节点
  flattenNodes(nodes) {
    return (nodes || []).reduce((res, node) => {
      return (node.nodes || []).reduce((res1, subNode, index) => {
        res1.push({
          title: index === 0 ? node.title : '', // 子节点中仅第一个显示title
          desc: subNode.status,
          date: formatTime(+subNode.timestamp, 'YYYY-MM-DD HH:mm:ss'),
          icon: index === 0 ? LogisticsIconMap[node.code] || '' : '', // 子节点中仅第一个显示icon
        });
        return res1;
      }, res);
    }, []);
  },

  datermineInvoiceStatus(order) {
    // 1-已开票
    // 2-未开票（可补开）
    // 3-未开票
    // 4-门店不支持开票
    return order.invoiceStatus;
  },

  // 拼接省市区
  composeAddress(order) {
    return [
        //order.logisticsVO.receiverProvince,
        // order.logisticsVO.receiverCity,
        order.logisticsVO.receiverCountry,
        order.logisticsVO.receiverArea,
        order.logisticsVO.receiverAddress,
      ]
      .filter((s) => !!s)
      .join(' ');
  },
  getStoreDetail() {
    fetchBusinessTime().then((res) => {
      const storeDetail = {
        storeTel: res.data.telphone,
        storeBusiness: res.data.businessTime.join('\n'),
      };
      this.setData({
        storeDetail
      });
    });
  },

  // 仅对待支付状态计算付款倒计时
  // 返回时间若是大于2020.01.01，说明返回的是关闭时间，否则说明返回的直接就是剩余时间
  computeCountDownTime(order) {
    if (order.orderStatus !== OrderStatus.PENDING_PAYMENT) return null;
    return order.autoCancelTime > 1577808000000 ?
      order.autoCancelTime - Date.now() :
      order.autoCancelTime;
  },

  onCountDownFinish() {
    //this.setData({ countDownTime: -1 });
    const {
      countDownTime,
      order
    } = this.data;
    if (
      countDownTime > 0 ||
      (order && order.groupInfoVo && order.groupInfoVo.residueTime > 0)
    ) {
      this.onRefresh();
    }
  },

  onGoodsCardTap(e) {
    const {
      index
    } = e.currentTarget.dataset;
    const goods = this.data.order.orderItemVOs[index];
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${goods.spuId}`
    });
  },
  onMobileTap(e) {
    const mobile = e.target.dataset.mobile
    wx.makePhoneCall({
      phoneNumber: mobile,
      success: res => {
        // console.log(res)
      },
      fail: res => {
        console.error(res)
      }
    })
  },

  onEditAddressTap() {
    getAddressPromise()
      .then((address) => {
        this.setData({
          'order.logisticsVO.receiverName': address.name,
          'order.logisticsVO.receiverPhone': address.phone,
          '_order.receiverAddress': address.address,
        });
      })
      .catch(() => {});

    wx.navigateTo({
      url: `/pages/usercenter/address/list/index?selectMode=1`,
    });
  },
  async onNickNameTap() {
    const user = this.data.user
    const orderUser = this.data.orderUser || (await this.loadOrderUser()).data[0]
    if (['admin'].indexOf(user.role) >= 0) return nav2.staffEdit('edit', orderUser._id)
    if (user._id == orderUser._id) return nav2.personInfo()
  },
  onOrderNumCopy() {
    wx.setClipboardData({
      data: this.data.order._id,
    });
  },

  onDeliveryNumCopy() {
    wx.setClipboardData({
      data: this.data.order.logisticsVO.logisticsNo,
    });
  },

  onToInvoice() {
    wx.navigateTo({
      url: `/pages/order/invoice/index?orderNo=${this.data._order.orderNo}`,
    });
  },

  onSuppleMentInvoice() {
    wx.navigateTo({
      url: `/pages/order/receipt/index?orderNo=${this.data._order.orderNo}`,
    });
  },

  onDeliveryClick() {
    const logisticsData = {
      nodes: this.data.logisticsNodes,
      company: this.data.order.logisticsVO.logisticsCompanyName,
      logisticsNo: this.data.order.logisticsVO.logisticsNo,
      phoneNumber: this.data.order.logisticsVO.logisticsCompanyTel,
    };
    wx.navigateTo({
      url: `/pages/order/delivery-detail/index?data=${encodeURIComponent(
        JSON.stringify(logisticsData),
      )}`,
    });
  },

  /** 跳转订单评价 */
  navToCommentCreate() {
    wx.navigateTo({
      url: `/pages/order/createComment/index?orderNo=${this.orderNo}`,
    });
  },

  /** 跳转拼团详情/分享页*/
  toGrouponDetail() {
    wx.showToast({
      title: '点击了拼团'
    });
  },
  clickService() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '您点击了联系客服',
    });
  },
  onOrderInvoiceView() {
    wx.navigateTo({
      url: `/pages/order/invoice/index?orderNo=${this.orderNo}`,
    });
  },

  async sendSms2User(user, orderUser, order) {
    if (['admin', 'master'].indexOf(user.role) < 0) return
    if (user._openid == order._openid) return // 当前用户自己的订单
    if (!orderUser.phoneNumber) return
    await wx.cloud.callFunction({
      name: 'sendSmsTc',
      data: {
        templateName: "custom_msg",
        templateParamList: [dateTool.format(new Date().getTime(), "M月d日h点"), "1"],
        phoneNumberList: ["+86" + orderUser.phoneNumber],
        sessionContext: 'notify order user'
      }
    })
  }
});